package com.library.manager.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(false);

        // 获取请求的URI
        String uri = req.getRequestURI();
        
        // 不需要过滤的路径
        if (uri.endsWith("login.html") || 
            uri.endsWith("register.html") || 
            uri.endsWith("login.manager") || 
            uri.endsWith("register.manager") ||
            uri.contains("/js/") ||
            uri.contains("/css/") ||
            uri.contains("/images/")) {
            chain.doFilter(request, response);
            return;
        }

        // 检查是否已登录
        if (session == null || session.getAttribute("manager") == null) {
            // 未登录，重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login.html");
            return;
        }

        // 已登录，继续请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
} 